﻿using SqlScriptVault.Commands;
using SqlScriptVault.Model;
using SqlScriptVault.Properties;
using SqlScriptVault.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace SqlScriptVault.ViewModel
{
    class LoginViewModel : BaseNotifyViewModel
    {
        private readonly IMessageDisplayService _messageDisplayService;

        public LoginViewModel(IMessageDisplayService messageDisplayService)
        {
            _messageDisplayService = messageDisplayService;            
        }

        public LoginViewModel()
            : this(new MessageDisplayService())
        {
        }

        public Server Server { get; set; }

        public string Username { get; set; }

        public SqlCredential SqlCredential { get; private set; }

        public event Action RequestClose;

        public RelayCommand CommitCommand
        {
            get
            {
                return new RelayCommand(param => Commit());
            }
        }

        public void Commit()
        {
            if (string.IsNullOrEmpty(Username))
            {
                return;
            }

            string password = (string)EventService.Instance.Publish(EventService.PasswordEvent, null);

            SqlCredential = new SqlCredential(Username, password);
            Settings settings = new Settings();

            try
            {
                string connectionString = string.Format(settings.ConnectionString, Server.ServerName, Server.DatabaseName, SqlCredential.Username, SqlCredential.Password);
                using (SqlConnection sqlConnection = new SqlConnection(connectionString))
                {
                    sqlConnection.Open();
                }
            }
            catch (Exception exception)
            {
                _messageDisplayService.ShowErrorMessage(string.Format("Connection failed: {0}", exception.Message));
                return;
            }

            RequestClose();
        }

        public void Initialize()
        {
            RaisePropertyChanged("Server");
        }
    }
}
